import { Effect, Reducer } from 'umi';

import { queryCurrent, query as queryUsers, getInfo } from '@/services/user';
import { getToken,setToken } from '@/utils/auth'

export interface CurrentUser {
  admin?: boolean;
  avatar?: string;
  email?: string;
  idCard?: string;
  nickName?: string;
  phonenumber?: string;
  sex?: string;
  userId?: number;
  userName?: string;
}

export interface UserModelState {
  currentUser?: CurrentUser;
  roles?: Array<string>;
  permissions?:Array<string>;
  token?: string;
}

export interface UserModelType {
  namespace: 'user';
  state: UserModelState;
  effects: {
    fetch: Effect;
    fetchCurrent: Effect;
    getInfo: Effect;
  };
  reducers: {
    saveCurrentUser: Reducer<UserModelState>;
    changeNotifyCount: Reducer<UserModelState>;
    setToken: Reducer<UserModelState>;
  };
}

const UserModel: UserModelType = {
  namespace: 'user',

  state: {
    currentUser: {},
    roles:[],
    permissions:[],
    token: getToken() || '',
  },

  effects: {
    *fetch(_, { call, put }) {
      const response = yield call(queryUsers);
      yield put({
        type: 'save',
        payload: response,
      });
    },
    *fetchCurrent(_, { call, put }) {
      const response = yield call(queryCurrent);
      yield put({
        type: 'saveCurrentUser',
        payload: response,
      });
    },
    *getInfo(_, { call, put }) {
      const response = yield call(getInfo);
      if (response.code == 200) {
        yield put({
          type: 'saveCurrentUser',
          payload: response
        })
      }
    },
  },

  reducers: {
    setToken(state, action) {
      setToken(action.payload)
      return {
        ...state,
        token: action.payload || ''
      }
    },
    saveCurrentUser(state, { payload }) {
      return {
        ...state,
        currentUser: payload.user || {},
        permissions: payload.permissions || [],
        roles: payload.roles || []
      }
    },
    changeNotifyCount(state,action) {
      return {
        ...state,
      };
    },
  },
};

export default UserModel;
